package com.yonyou.jrmob.lryapp;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.google.gson.Gson;
import com.pgyersdk.update.PgyUpdateManager;
import com.umeng.analytics.MobclickAgent;
import com.yonyou.jr.mob.rzkh.R;
import com.yonyou.jrmob.application.bean.TaskBean;
import com.yonyou.jrmob.application.ui.fragment.MainAppFragment;
import com.yonyou.jrmob.contacts.contact.fragment.ContactsMainFragment_ct;
import com.yonyou.jrmob.lryapp.fragment.MyFragment;
import com.yonyou.uap.emm.http.HttpCallback;
import com.yonyou.uap.emm.util.EmmUtil;
import com.yonyou.uap.emm.util.PhoneInfo;
import com.yonyou.uap.um.service.ServiceCallback;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import jrmob.yonyou.com.commonlib.app_config_tool.constant.Constant;
import jrmob.yonyou.com.commonlib.app_config_tool.gkh.MAServices_gkh;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.HttpUtil;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.base.CommonUtil;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.base.LogUtils;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.base.MobUtils;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.base.StatusBarUtil;
import jrmob.yonyou.com.commonlib.baseui.base.BaseActivityMob_lib;
import jrmob.yonyou.com.commonlib.baseui.base.BaseApp_lib;
import jrmob.yonyou.com.commonlib.login.bean.LoginBean;
import jrmob.yonyou.com.commonlib.login.bean.UserInfoLRY;
import jrmob.yonyou.com.commonlib.vo.AppVO_ap;


public class MainActivity extends BaseActivityMob_lib implements AMapLocationListener {
    private static final int FINISHED_CALL_WEB_APP = 1;
    @BindView(R.id.main_fragment_container)
    FrameLayout mainFragmentContainer;
    @BindView(R.id.main_navigation_bar)
    BottomNavigationView mainNavigationBar;
    FragmentManager fm;
    @BindView(R.id.main_progress)
    ProgressBar mainProgress;
    private MainAppFragment mainAppFragment;
    private ContactsMainFragment_ct contactsMainFragmentCt;

    //定位
    private AMapLocationClient mLocationClient;
    private AMapLocationClientOption mLocationOption;
    private Boolean isFirstLocation = true;

    private boolean isExit = false;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == FINISHED_CALL_WEB_APP) {
                initFragment();
            }
        }
    };
    private Dialog loadingDialog;
    private String url;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        StatusBarUtil.setStatusBarColor(this, R.color.login_titlebar);
        //登录成功到主界面加载主界面数据
        callServiceData();
        callServiceListData();
        initNav();

        checkVersion();
        tempStatus = 1;

         /*开始定位*/
        startLocation();
        //蒲公英升级update
        PgyUpdateManager.register(this);
    }

    private void callServiceData() {
        mainProgress.setVisibility(View.VISIBLE);
        try {
            JSONObject json = new JSONObject();

            String ip = readLocationValue(Constant.MA_IP);
            String port = readLocationValue(Constant.MA_PORT);
            if (TextUtils.isEmpty(ip)) {
                showToast("请设置IP!");
                return;
            }

            BaseApp_lib.setIp_gkh(ip);
            BaseApp_lib.setPort_gkh(port);

            // 请求接口服务类型()
            json.put("transtype", "urlparamrequest");
            json.put("chamc_mobiletoken", "");
            json.put("username", readLocationValue(Constant.LOGIN_USER_NAME));
            JSONObject json2 = new JSONObject();
            json2.put("Authority", "u_usercode=" + readLocationValue("login_userId") + ";"
                    + "tenantid=" + readLocationValue("login_tenantId") + ";"
                    + "token=" + readLocationValue("login_token") + ";"
                    + "u_logints=" + readLocationValue("login_u_logints"));
            json.put("reqheader", json2);
            //需要变动的参数
            json.put("requrl", Constant.REQ_URL);
            json.put("reqparam", "username=" + readLocationValue(Constant.LOGIN_USER_NAME)
                    + "&password=" + readLocationValue(Constant.LOGIN_USER_PWD));
            // 请求服务方式
            json.put("requestMethod", "POST");
            json.put("reqmethod", "post");

            if (!CommonUtil.isNetworkConnected(this)) {
                CommonUtil.showToast(this, "当前网络不可用,请检查!");
                return;
            }
            MAServices_gkh.callMACommonService(MainActivity.this, new ServiceCallback() {
                @Override
                public void execute(JSONObject jsonObject) {

                    LogUtils.e("首页数据：" + jsonObject.toString());
                    try {

                        // 有错误的时候
                        if (jsonObject.opt("success") != null && !jsonObject.optBoolean("success")) {
                            showMessage("获取数据失败!");
                            mainProgress.setVisibility(View.INVISIBLE);
                            return;
                        }

                        JSONObject userInfo = jsonObject.optJSONObject("loginInfo");
                        if (userInfo == null) {
                            showMessage("获取数据失败!!");
                            mainProgress.setVisibility(View.INVISIBLE);
                            return;
                        }

                        String toObject = jsonObject.toString();

                        Gson gson = new Gson();
                        LoginBean object = gson.fromJson(toObject, LoginBean.class);
                        saveDataToLocal(object);

                    } catch (Exception e1) {
                        LogUtils.e(e1);
                        e1.printStackTrace();
                        mainProgress.setVisibility(View.INVISIBLE);
                    }
                    //LogUtils.e(jsonObject.toString());
                }

                @Override
                public void error(String s, String s1) {
                    mainProgress.setVisibility(View.INVISIBLE);
                    showMessage(s + s1);
                    LogUtils.e(s + " " + s1);
                }
            }, json, MAServices_gkh.initMaRequestUrl());
        } catch (Exception e) {
            mainProgress.setVisibility(View.INVISIBLE);
            e.printStackTrace();
        }
    }

    private void callServiceListData() {
        /*OkGo.get(Constant.REQ_URL_DATA_LIST)//
                .tag(this)//
                .params("start", "0")//  这里不要使用params，upJson 与 params 是互斥的，只有 upJson 的数据会被上传
                //.upJson(jsonObject.toString())//
                .params("size","100")
                .params("taskFlag","todo")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        //上传成功
                        Log.i("LOGINLIST",s);
                        try {
                            Gson gson = new Gson();
                            TaskBean object = gson.fromJson(s,TaskBean.class);

                            List<TaskBean.DataBeanX.DataBean> messageBeanList = object.getData().getData();
                            writeLocationObject(Constant.task_list, messageBeanList);
                            EventBus.getDefault().post("finised");

                        } catch (Exception e1) {
                            LogUtils.e(e1);
                            e1.printStackTrace();
                        }
                        LogUtils.e(s);
                    }


                    @Override
                    public void upProgress(long currentSize, long totalSize, float progress, long networkSpeed) {
                        //这里回调上传进度(该回调在主线程,可以直接更新ui)
                    }
                });*/
        try {
            JSONObject json = new JSONObject();

            String ip = readLocationValue(Constant.MA_IP);
            String port = readLocationValue(Constant.MA_PORT);
            if (TextUtils.isEmpty(ip)) {
                showToast("请设置IP!");
                return;
            }

            BaseApp_lib.setIp_gkh(ip);
            BaseApp_lib.setPort_gkh(port);

            // 请求接口服务类型()
            json.put("transtype", "urlparamrequest");
            json.put("chamc_mobiletoken", "");
            json.put("username", readLocationValue(Constant.LOGIN_USER_NAME));
            JSONObject json2 = new JSONObject();
            json2.put("Authority", "u_usercode=" + readLocationValue("login_userId") + ";"
                    + "tenantid=" + readLocationValue("login_tenantId") + ";"
                    + "token=" + readLocationValue("login_token") + ";"
                    + "u_logints=" + readLocationValue("login_u_logints"));
            json.put("reqheader", json2);
            //需要变动的参数
            json.put("requrl", Constant.REQ_URL_DATA_LIST);
            json.put("reqparam", "start=0" + "&size=100" + "&taskFlag=todo");
            // 请求服务方式
            json.put("requestMethod", "GET");
            json.put("reqmethod", "get");

            if (!CommonUtil.isNetworkConnected(this)) {
                CommonUtil.showToast(this, "当前网络不可用,请检查!");
                return;
            }
            MAServices_gkh.callMACommonService(MainActivity.this, new ServiceCallback() {
                @Override
                public void execute(JSONObject jsonObject) {

                    LogUtils.e("LOGINLIST：" + jsonObject.toString());
                    //上传成功
                    try {
                        Gson gson = new Gson();
                        TaskBean object = gson.fromJson(jsonObject.toString(), TaskBean.class);

                        List<TaskBean.DataBeanX.DataBean> messageBeanList = object.getData().getData();
                        writeLocationObject(Constant.task_list, messageBeanList);
                        EventBus.getDefault().post("finised");

                    } catch (Exception e1) {
                        LogUtils.e(e1);
                        e1.printStackTrace();
                    }
                    //LogUtils.e(jsonObject.toString());
                }

                @Override
                public void error(String s, String s1) {
                    showMessage(s + s1);
                    LogUtils.e(s + " " + s1);
                }
            }, json, MAServices_gkh.initMaRequestUrl());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        callServiceListData();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    /**
     * 保存小部件的对应的数值
     *
     * @param loginBean 登录接口返回的结果
     */
    private void saveDataToLocal(LoginBean loginBean) {

        String customer_count = loginBean.getCustomer_count();
        String payment_count = loginBean.getPayment_count();
        String contract_money = loginBean.getContract_money();
        String task_count = loginBean.getTask_count();

        writeLocationFile(Constant.payment_count, payment_count);
        writeLocationFile(Constant.customer_count, customer_count);
        writeLocationFile(Constant.contract_money, contract_money);
        writeLocationFile(Constant.task_count, task_count);


        UserInfoLRY userInfoLRY = new UserInfoLRY();
        userInfoLRY.setTenant_id(loginBean.getLoginInfo().getTenantId());
        userInfoLRY.setCode(loginBean.getLoginInfo().getUsername());
        userInfoLRY.setUser_code(loginBean.getLoginInfo().getUsername());
        userInfoLRY.setUser_id(loginBean.getLoginInfo().getUserId());
        userInfoLRY.setUser_name(loginBean.getLoginInfo().getUsername());
        userInfoLRY.setToken(loginBean.getLoginInfo().getToken());

        userInfoLRY.setContract_money(contract_money);
        userInfoLRY.setPayment_count(payment_count);
        userInfoLRY.setCustomer_count(customer_count);
        userInfoLRY.setTask_count(task_count);

        writeLocationObject(Constant.userInfoLry, userInfoLRY);

        List<LoginBean.AppAuthBean> appAuths = loginBean.getAppAuth();
        writeLocationObject(Constant.app_auth, appAuths);

        // 刚进来加载所有应用列表
        loadapplistinfo(true);

    }


    private void initFragment() {
        mainProgress.setVisibility(View.INVISIBLE);
        mainAppFragment = new MainAppFragment();
        contactsMainFragmentCt = new ContactsMainFragment_ct();
        fm = getSupportFragmentManager();
        fm.beginTransaction().replace(R.id.main_fragment_container, mainAppFragment).commit();
    }

    private void initNav() {
        mainNavigationBar.setItemIconTintList(null);
        mainNavigationBar.setItemTextColor(getResources().getColorStateList(R.color.selector_nav_color));
        mainNavigationBar.getMenu().getItem(0).setIcon(R.drawable.icon_main_page_press);
        mainNavigationBar.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menu_main_main_page:
                        item.setIcon(R.drawable.icon_main_page_press);
                        mainNavigationBar.getMenu().getItem(2).setIcon(R.drawable.icon_my_normal);
                        mainNavigationBar.getMenu().getItem(1).setIcon(R.drawable.icon_contacts_normal);
                        if (null != mainAppFragment) {
                            fm.beginTransaction().replace(R.id.main_fragment_container, mainAppFragment).commit();
                        }
                        break;
                    case R.id.menu_main_contact:

                        //showMessage("有待开发");
                        item.setIcon(R.drawable.icon_contacts_press);
                        mainNavigationBar.getMenu().getItem(0).setIcon(R.drawable.icon_main_page_normal);
                        mainNavigationBar.getMenu().getItem(2).setIcon(R.drawable.icon_my_normal);
                        if (null != contactsMainFragmentCt) {
                            getSupportFragmentManager().beginTransaction().replace(R.id.main_fragment_container, contactsMainFragmentCt).commit();
                        }
//
                        break;
                    case R.id.menu_main_my:
                        item.setIcon(R.drawable.icon_my_press);
                        mainNavigationBar.getMenu().getItem(0).setIcon(R.drawable.icon_main_page_normal);
                        mainNavigationBar.getMenu().getItem(1).setIcon(R.drawable.icon_contacts_normal);
                        getSupportFragmentManager().beginTransaction().replace(R.id.main_fragment_container, new MyFragment()).commit();
                        break;
                }
                return true;
            }
        });
    }

    @Override
    public void initView() {

    }

    @Override
    public void initListener() {

    }

    @Override
    public void initData() {
        if (LRYApplication.model == null || TextUtils.isEmpty(LRYApplication.model)) {
            PhoneInfo info = new PhoneInfo(this);
            LRYApplication.model = info.getModel();
        }
    }

    //监听返回键

    @Override
    public void onBackPressed() {
        exit();
    }

    private void exit() {
        if (!isExit) {
            isExit = true;
            Toast.makeText(mActivity, "再按一次退出应用程序！", Toast.LENGTH_SHORT).show();
            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false;
                }
            }, 2000);
        } else {
            System.exit(0);
        }
    }

    /*********** 加载 emm 上面的应用列表 start *********/


    /**
     * 加载applistinfo
     */
    public void loadapplistinfo(final boolean isupdate) {
        // 获取列表信息
        JSONObject json = new JSONObject();
        try {
            String user = Constant.emmUserName;
            // 利用登录账号读取 emm 应用信息
            String usercode_rzzl = readLocationValue("usercode_rzzl");
            if (!TextUtils.isEmpty(usercode_rzzl)) {
                //user = usercode_rzzl;
            }
            if (!TextUtils.isEmpty(user)) {
                json.put("userid", user);
                json.put("deviceid", MobUtils.getDeviceId(this));
                json.put("os", "android");
                // 标识是否立即更新
                getAppList(this, "none", json, callback2);
            }


        } catch (Exception e) {
            LogUtils.e(e);
        }


    }


    /**
     * @param context
     * @param tp       加密类型
     * @param data     数据  参数 JSONObject data = new JSONObject();
     *                 p.put("userid", "");
     *                 p.put("deviceid", "");
     *                 p.put("os", "android");
     * @param callBack
     */
    public void getAppList(Context context, final String tp, final JSONObject data, final HttpCallback callBack) {

        //10.15.0.111:8010
        Map map = BaseApp_lib.getMap_app();
        map.put("emm_ip", Constant.emmIP);
        map.put("emm_port", Constant.emmPORT);

        if (!TextUtils.isEmpty(Constant.emmIP)) {
            if (Constant.HTTP_emm.equals("https") && TextUtils.isEmpty(Constant.emmPORT)) {
                String emm_emm = map.get("emm_ip") + "";
                url = "https://" + emm_emm + "/mobem/app/getapps";
                LogUtils.e("emm_emm: " + emm_emm);
            } else if (Constant.HTTP_emm.equals("http") && !TextUtils.isEmpty(Constant.emmPORT)) {
                String emm_emm = map.get("emm_ip") + ":" + map.get("emm_port");
                url = "http://" + emm_emm + "/mobem/app/getapps";
                LogUtils.e("emm_emm: " + emm_emm);
            } else if (Constant.HTTP_emm.equals("http") && TextUtils.isEmpty(Constant.emmPORT)) {
                String emm_emm = map.get("emm_ip") + "";
                url = "http://" + emm_emm + "/mobem/app/getapps";
                LogUtils.e("emm_emm: " + emm_emm);
            }
            LogUtils.e("emm_emm" + url);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        EmmUtil.getRequest(url, tp, data.toString(), callBack);
                    } catch (Exception e) {
                        LogUtils.e("emm_emm" + e);
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }


    HttpCallback callback2 = new HttpCallback() {
        @Override
        public void execute(String s) {

            LogUtils.e("emm_emm" + s);
            if (null != s) {
                try {
                    JSONObject json = new JSONObject(s);
                    String tp = json.optString("tp", "none");
                    String data = json.optString("data", "");
                    if (!TextUtils.isEmpty(data)) {
                        JSONObject jsondata = new JSONObject(data);
                        String code = jsondata.optString("code", "");
                        String msg = jsondata.optString("msg", "");
                        JSONArray apps = jsondata.optJSONArray("apps");
                        LogUtils.e("apps: " + apps);

                        if (null != apps) {
                            // 数据为空的时候不处理
                            if (apps.length() == 0) {
                                return;
                            }

                            BaseApp_lib.setAppslist(null);
                            BaseApp_lib.setAppslist(new ArrayList<AppVO_ap>());
                            JSONObject jsonObject;
                            List<AppVO_ap> tempappList = BaseApp_lib.getAppslist();
                            for (int i = 0; i < apps.length(); i++) {
                                AppVO_ap vo = new AppVO_ap();
                                jsonObject = apps.getJSONObject(i);

                                vo.setAppname(jsonObject.optString("title", ""));
                                vo.setAppid(jsonObject.optString("applicationId", ""));
                                vo.setAppcode(jsonObject.optString("title", ""));
                                vo.setApptype("0");
                                vo.setWebzipurl(jsonObject.optString("webzipurl", ""));
                                vo.setWebiconurl(jsonObject.optString("webiconurl", ""));
                                vo.setWebversion(jsonObject.optString("webversion", ""));
                                vo.setApptype("2");
                                tempappList.add(vo);
                            }


                            List<AppVO_ap> appslist = BaseApp_lib.getAppslist();
                            if (appslist.size() != 0) { // 说明有 h5的应用
                                orderApps(appslist);
                            } else {
                                Message message = Message.obtain();
                                message.what = FINISHED_CALL_WEB_APP;
                                mHandler.sendMessage(message);
                            }
                        }
                    } else {
                        Message message = Message.obtain();
                        message.what = FINISHED_CALL_WEB_APP;
                        mHandler.sendMessage(message);
                    }
                } catch (Exception e) {
                    LogUtils.e("emm_emm" + e);
                }
            }
        }
    };

    /**
     * 对H5应用进行排序
     * 思路：首先申请一个list，长度为{appAuths，appsList， appAuth.sort}中的最大值，list的每一个原素先置位空，然后调用list.add(appAuth.sort, APPVO)
     * 这样就给原有的appsList排好序了，排好序后把里面的null剔除掉
     *
     * @param appslist
     */
    private void orderApps(List<AppVO_ap> appslist) {
        ArrayList<LoginBean.AppAuthBean> appAuths = readLocationObject(Constant.app_auth, ArrayList.class);
        if (appAuths == null || appAuths.size() == 0) {
            //return;
        }
        ArrayList<AppVO_ap> tempOrderedAppVO_aps = new ArrayList<>();

        //获取最大值
        int authSortMax = 0;
        for (LoginBean.AppAuthBean appAuth : appAuths) {
            if (!TextUtils.isEmpty(appAuth.getApp_sort())) {
                authSortMax = Math.max(authSortMax, Integer.parseInt(appAuth.getApp_sort()));
            }
        }
        int max = Math.max(appAuths.size(), appslist.size());
        max = Math.max(max, authSortMax);

        //申请一个长度为最大值的list，每一个元素都为null
        for (int i = 0; i < max; i++) {
            tempOrderedAppVO_aps.add(null);
        }
        //排序
        for (LoginBean.AppAuthBean appAuth : appAuths) {
            for (AppVO_ap appVO_ap : appslist) {
                if (appVO_ap.getAppid().equals(appAuth.getApp_code())) {
                    tempOrderedAppVO_aps.add(Integer.parseInt(appAuth.getApp_sort()), appVO_ap);
                }
            }
        }

        //剔除空的元素
        Iterator<AppVO_ap> iterator = tempOrderedAppVO_aps.iterator();
        while (iterator.hasNext()) {
            AppVO_ap appVOAp = iterator.next();
            if (appVOAp == null) {
                iterator.remove();
            }
        }

        if (Constant.ma_ip.equals("117.121.129.32")) {
            //手机验证
            /*AppVO_ap appVO_ap0 = new AppVO_ap();
            appVO_ap0.setAppname(Constant.EXTRA_H5_APP);
            appVO_ap0.setAppid("mifeng");
            tempOrderedAppVO_aps.add(appVO_ap0);*/
            //移动审批
            AppVO_ap appVO_ap1 = new AppVO_ap();
            appVO_ap1.setAppname(Constant.EXTRA_H5_YIDONGSHENPI);
            appVO_ap1.setAppid("yidongshenpi");
            tempOrderedAppVO_aps.add(appVO_ap1);

            //车E估
            AppVO_ap appVO_ap2 = new AppVO_ap();
            appVO_ap2.setAppname(Constant.EXTRA_H5_CHEEGU);
            appVO_ap2.setAppid("cheyigu");
            tempOrderedAppVO_aps.add(appVO_ap2);
            // 写到本地
            writeLocationObject(Constant.appsinfo, tempOrderedAppVO_aps);

            Message message = Message.obtain();
            message.what = FINISHED_CALL_WEB_APP;
            mHandler.sendMessage(message);
        } else {
            //手机验证
            AppVO_ap appVO_ap0 = new AppVO_ap();
            appVO_ap0.setAppname(Constant.EXTRA_H5_APP);
            appVO_ap0.setAppid("mifeng");
            tempOrderedAppVO_aps.add(appVO_ap0);
            //移动审批
            AppVO_ap appVO_ap1 = new AppVO_ap();
            appVO_ap1.setAppname(Constant.EXTRA_H5_YIDONGSHENPI);
            appVO_ap1.setAppid("yidongshenpi");
            tempOrderedAppVO_aps.add(appVO_ap1);

            //车E估
            AppVO_ap appVO_ap2 = new AppVO_ap();
            appVO_ap2.setAppname(Constant.EXTRA_H5_CHEEGU);
            appVO_ap2.setAppid("cheyigu");
            tempOrderedAppVO_aps.add(appVO_ap2);
            // 写到本地
            writeLocationObject(Constant.appsinfo, tempOrderedAppVO_aps);

            Message message = Message.obtain();
            message.what = FINISHED_CALL_WEB_APP;
            mHandler.sendMessage(message);
        }

    }


    /*********** 加载 emm 上面的应用列表 end *********/


    /*********************自动更新**********************/
    /**
     * 功能: 检查版本更新
     * <p/>
     * 日 期: 2016/7/14
     */
    private void checkVersion() {

        if (!CommonUtil.isNetworkConnected(this)) {
            Toast.makeText(mActivity, "当前网络不可用，请检查！", Toast.LENGTH_SHORT).show();
            return;
        }

        try {
            new Thread(new Runnable() {
                @Override
                public void run() {

                    Object result = HttpUtil.sendPost("https://appstore.yonyou.com/sites/update.php",
                            "type=apk&&name=" + getResources().getString(R.string.description));

                    Message message = Message.obtain();
                    message.what = 90000;
                    message.obj = result;

                    handler.sendMessage(message);
                }
            }).start();
        } catch (Exception e) {
            LogUtils.e("eeee: " + e);
        }
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {

                case 90000:

                    // 校验
                    checkJudeyApkVersion(msg.obj + "");

                    break;

                default:

                    break;
            }
        }

    };


    private void checkJudeyApkVersion(String info) {

        try {
            LogUtils.e(info + "");
            JSONObject json = new JSONObject(info);
            int code = json.optInt("code", 1);
            String message = json.optString("msg", "错误");
            String versionCode = json.optString("versionCode", "1.0");
            String update_url = json.optString("update_url", "www.baidu.com");
            String update_msg = json.optString("update_msg", "更新出错啦!");
            //username.setText(msg.obj+"");
            if (message.equals("检测更新成功")) {
                //保存下载地址和版本
                updateVersionInfo(update_url, versionCode);
                //检查版本
                if (checkupdateVersion()) {
                    new AlertDialog.Builder(this)
                            .setTitle(update_msg)
                            .setMessage("检测到有新的版本,是否更新到" + versionCode + "版本")
                            .setNegativeButton(
                                    "更新",
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(
                                                DialogInterface dialog,
                                                int which) {

                                            String update_url = readLocationValue("update_url");

                                            LogUtils.e("从本地读取update_url = " + update_url);
                                            if (!TextUtils.isEmpty(update_url)) {
                                                updateAppVersion(update_url);
                                            } else {
                                                mActivity.showToast("更新路径URL有误!");
                                            }
                                        }

                                    })
                            .setPositiveButton(
                                    "取消",
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(
                                                DialogInterface dialog,
                                                int which) {
                                            dialog.dismiss();
                                                    /*Message message = Message.obtain();
                                                    message.what = 0; // 登录成功
                                                    // 不需要更新
                                                    handler.sendMessage(message);*/

                                        }
                                    }).setCancelable(false).show();
                }
            } else {
                //showToast("检测更新失败");
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    /**
     * 更新升级版本
     * update_url apk现在地址
     * versioncode 新的apk对应的版本号
     */
    private void updateVersionInfo(String update_url, String versioncode) {

        // 记录下,后台的版本信息
        writeLocationFile("app_version", versioncode + "");
        writeLocationFile("update_url", update_url);

    }


    /**
     * 检查更新
     */
    private boolean checkupdateVersion() {

        String app_version = readLocationValue("app_version");
        if (!TextUtils.isEmpty(app_version)) {
            if (!TextUtils.isEmpty(getVersionName())) {
                int oldversion = getVersionNum(getVersionName());
                int newversion = getVersionNum(app_version);
                // 判断是否需要更新
                if (newversion > oldversion) {
                    return true;
                }
            } else {
                return false;
            }

        }
        return false;
    }

    private int getVersionNum(String VersionName) {
        String[] curCodeArray = VersionName.split("\\.");
        StringBuilder curVersionCodeStr = new StringBuilder();
        for (int i = 0; i < curCodeArray.length; i++) {
            curVersionCodeStr.append(curCodeArray[i]);
        }
        //服务器版本号
        int VersionNum = Integer.parseInt(curVersionCodeStr + "");
        return VersionNum;
    }


    /**
     * 更新app,转到url
     *
     * @param url
     */
    private void updateAppVersion(String url) {
        // 不为空,到升级网址
        if (!TextUtils.isEmpty(url)) {
            Uri uri = Uri.parse(url);
            Intent it = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(it);
        }
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {
            String address = aMapLocation.getAddress();
            writeLocationFile("address", address);
            //Toast.makeText(mActivity, "定位成功"+address, Toast.LENGTH_SHORT).show();
            LogUtils.e("ADDRESS",address);
            if (isFirstLocation) {
                isFirstLocation = false;
            }
        } else {
            if (isFirstLocation) {
                isFirstLocation = false;
                String errText = "获取定位信息失败...";
                mLocationClient.startLocation();
                //Toast.makeText(this, errText, Toast.LENGTH_SHORT).show();
            }
        }
    }

    //开始定位
    private void startLocation() {
        //定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(this);
        mLocationOption = new AMapLocationClientOption();
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //mLocationOption.setInterval(30000);
        mLocationOption.setOnceLocation(true);
        mLocationClient.setLocationOption(mLocationOption);
        mLocationClient.startLocation();
    }

/*********************自动更新结束**********************/
}
